/*
 * @Author: hongbin
 * @Date: 2022-11-22 12:14:33
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-22 12:24:19
 * @Description:发送消息
 */
import { ObjectId } from "mongodb";
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../../src/api/utils";
import DB from "../mongodb";
import { receiveRequest } from "../utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    if (!receiveRequest(req, res, "POST")) return;
    // 通过socket发送申请加好友消息同意后双方均执行此请求
    console.log("消息内容:", req.body);
    if (!VerifyFields.has(req.body, ["recordId", "sender", "type", "content"])) {
        return res.status(500).json("缺少关键字段");
    }

    const db = await DB;

    const date = Date.now();
    const _id = new ObjectId(req.body.recordId);
    const record = {
        date,
        sender: req.body.sender,
        type: req.body.type,
        content: req.body.content,
    };

    //向record 数组添加 消息
    const chatRecord = await db.collection("chatRecord").updateOne({ _id }, { $push: { record } });

    if (!chatRecord.acknowledged) {
        return res.status(200).json({ data: null, msg: "发送信息失败", code: -1 });
    }
    console.log("发送成功");
    res.json({ data: record });
}
